<template>
  <div class="app-container">
    <el-page-header @back="goBack" content="海报设计"></el-page-header>
    <h3></h3>
    <el-form :model="baseInfo" ref="baseInfo" :rules="baseInfoRules">
      <el-form-item :label-width="labelWidth" label="海报名称" prop="name">
        <el-input v-model="baseInfo.name" placeholder="请输入海报名称">
        </el-input>
      </el-form-item>
      <el-form-item
        label="海报关键字"
        :label-width="labelWidth"
        prop="keywords"
      >
        <el-input v-model="baseInfo.keywords" placeholder="请输入海报关键字">
        </el-input>
      </el-form-item>

      <el-form-item label="海报设计" prop="img" :label-width="labelWidth">
        <div class="poster_wrap" style="display: flex">
          <div class="poster" ref="poster">
            <!-- <el-image
              fit="cover"
              draggable="false"
              @mousedown.prevent
              v-if="baseInfo.bg_img"
              :src="baseInfo.bg_img"
            >
            </el-image> -->
            <img
              v-if="baseInfo.bg_img_show"
              ref="bgImg"
              :src="baseInfo.bg_img_show"
              draggable="false"
              @mousedown.prevent
              style="width: 100%; max-height: 100%"
              alt=""
            />
            <Drag
              ref="avatar"
              minX="0"
              minY="0"
              :maxX="getMaxX"
              :maxY="getMaxY"
              v-if="isShowAvatar"
              :rectMaxWidth="getMaxX"
              :rectMaxHeight="getMaxY"
              dragIconSize="6"
              :rectWidth="baseInfo.avatar_info.width"
              :rectHeight="baseInfo.avatar_info.height"
              :rectDefaultLeft="baseInfo.avatar_info.left"
              :rectDefaultTop="baseInfo.avatar_info.top"
            >
              <!-- 
                @/assets/404_images/404_cloud.png -->
              <img
                @click="eleClick('avatar')"
                @mousedown.prevent
                src="@/assets/images/avatar.jpg"
                style="width: 100%; height: 100%"
                alt=""
              />
              <!-- <img class="pic-404__parent" src="@/assets/404_images/404.png" alt="404"> -->
            </Drag>
            <Drag
              ref="nickname"
              minX="0"
              minY="0"
              :maxX="getMaxX"
              :maxY="getMaxY"
              :rectWidth="baseInfo.nickname_info.width || 80"
              :rectHeight="baseInfo.nickname_info.height || 30"
              v-if="isShowNickname"
              :rectMaxWidth="getMaxX"
              dragIconSize="6"
              :rectMaxHeight="getMaxY"
              rectBackgroundColor="transparent"
              :rectDefaultLeft="baseInfo.nickname_info.left"
              :rectDefaultTop="baseInfo.nickname_info.top"
            >
              <div
                @click="eleClick('nickname')"
                :style="{
                  lineHeight: 'normal',
                  fontSize: baseInfo.nickname_info.font_size + 'px',
                  color: baseInfo.nickname_info.font_color,
                }"
              >
                昵称
              </div>
            </Drag>

            <Drag
              ref="qrcode"
              minX="0"
              minY="0"
              :maxX="getMaxX"
              dragIconSize="6"
              :maxY="getMaxY"
              v-if="isShowQrcode"
              :rectMaxWidth="getMaxX"
              :rectMaxHeight="getMaxY"
              :rectWidth="baseInfo.qrcode_info.width"
              :rectHeight="baseInfo.qrcode_info.height"
              :rectDefaultLeft="baseInfo.qrcode_info.left"
              :rectDefaultTop="baseInfo.qrcode_info.top"
            >
              <img
                @click="eleClick('qrcode')"
                @mousedown.prevent
                src="@/assets/images/qrcode.png"
                style="width: 100%; height: 100%"
                alt=""
              />
            </Drag>
            <Drag
              ref="date"
              minX="0"
              minY="0"
              :maxX="getMaxX"
              :maxY="getMaxY"
              :rectWidth="baseInfo.date_info.width || 80"
              :rectHeight="baseInfo.date_info.height || 30"
              :rectDefaultLeft="baseInfo.date_info.left"
              :rectDefaultTop="baseInfo.date_info.top"
              v-if="isShowDate"
              :rectMaxWidth="getMaxX"
              dragIconSize="6"
              :rectMaxHeight="getMaxY"
              rectBackgroundColor="transparent"
            >
              <div
                @click="eleClick('date')"
                :style="{
                  lineHeight: 'normal',
                  fontSize: baseInfo.date_info.font_size + 'px',
                  color: baseInfo.date_info.font_color,
                }"
              >
                {{ getCurDate }}
              </div>
            </Drag>
            <Drag
              ref="time"
              minX="0"
              minY="0"
              :maxX="getMaxX"
              :maxY="getMaxY"
              :rectWidth="baseInfo.time_info.width || 80"
              :rectHeight="baseInfo.time_info.height || 30"
              :rectDefaultLeft="baseInfo.time_info.left"
              :rectDefaultTop="baseInfo.time_info.top"
              v-if="isShowTime"
              :rectMaxWidth="getMaxX"
              dragIconSize="6"
              :rectMaxHeight="getMaxY"
              rectBackgroundColor="transparent"
            >
              <div
                @click="eleClick('time')"
                :style="{
                  lineHeight: 'normal',
                  fontSize: baseInfo.time_info.font_size + 'px',
                  color: baseInfo.time_info.font_color,
                }"
              >
                {{ getCurTime }}
              </div>
            </Drag>
            <!-- 过期时间 -->
            <Drag
              ref="expire_time"
              minX="0"
              minY="0"
              :maxX="getMaxX"
              :maxY="getMaxY"
              :rectWidth="baseInfo.expire_time_info.width || 210"
              :rectHeight="baseInfo.expire_time_info.height || 30"
              :rectDefaultLeft="baseInfo.expire_time_info.left"
              :rectDefaultTop="baseInfo.expire_time_info.top"
              v-if="isShowExpireTime"
              :rectMaxWidth="getMaxX"
              dragIconSize="6"
              :rectMaxHeight="getMaxY"
              rectBackgroundColor="transparent"
            >
              <div
                @click="eleClick('expire_time')"
                :style="{
                  lineHeight: 'normal',
                  fontSize: baseInfo.expire_time_info.font_size + 'px',
                  color: baseInfo.expire_time_info.font_color,
                }"
              >
                {{ getExpireTime }}
              </div>
            </Drag>
          </div>
          <div class="right" style="flex: 1">
            <div class="item">
              <span style="margin-right: 50px">海报底图</span>
              <BtnImgUpload
                @uploadSuccess="imgUploadSuccess"
                :uploadImgUrl="uploadUrl"
              ></BtnImgUpload>
              <!-- <el-button type="primary" @click="upload">上传图片</el-button> -->
              <!-- <h6 class="tip">宽度为375px高度不限</h6> -->
            </div>
            <div class="item">
              <span style="margin-right: 50px">海报元素</span>
              <div class="btn-group">
                <el-button
                  class="mr_30"
                  size="small"
                  type="primary"
                  icon="UserFilled"
                  @click="addEle('isShowAvatar', 'avatar')"
                  >头像</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  icon="Notification"
                  class="mr_30"
                  @click="addEle('isShowNickname', 'nickname')"
                  >昵称</el-button
                >
                <el-button
                  icon="Calendar"
                  size="small"
                  type="primary"
                  class="mr_30"
                  @click="addEle('isShowQrcode', 'qrcode')"
                  >二维码</el-button
                >
                <el-button
                  size="small"
                  icon="Calendar"
                  type="primary"
                  class="mr_30"
                  @click="addEle('isShowDate', 'date')"
                  >日期</el-button
                >
                <el-button
                  icon="AlarmClock"
                  size="small"
                  type="primary"
                  class="mr_30"
                  @click="addEle('isShowTime', 'time')"
                  >时分</el-button
                >
                <el-button
                  icon="AlarmClock"
                  size="small"
                  type="primary"
                  class="mr_30"
                  @click="addEle('isShowExpireTime', 'expire_time')"
                  >过期时间</el-button
                >
                <el-button
                  v-if="isShowDelBtn"
                  @click="del"
                  icon="Delete"
                  size="small"
                  type="danger"
                  class="mr_30"
                  >删除</el-button
                >
              </div>
            </div>
            <div class="item" v-if="baseInfo[curSelectMapBaseInfo[curSelect]]">
              <span style="margin-right: 50px">字体颜色</span>
              <el-input
                v-model="baseInfo[curSelectMapBaseInfo[curSelect]].font_color"
                placeholder="请输入字体颜色"
              >
                <template #append>
                  <el-color-picker
                    style="height: 100%"
                    v-model="
                      baseInfo[curSelectMapBaseInfo[curSelect]].font_color
                    "
                  ></el-color-picker
                ></template>
              </el-input>
            </div>
            <div class="item" v-if="baseInfo[curSelectMapBaseInfo[curSelect]]">
              <span style="margin-right: 50px">字体大小</span>
              <el-input
                v-model="baseInfo[curSelectMapBaseInfo[curSelect]].font_size"
                placeholder="请输入字体大小"
              >
                <template #append>PX</template>
              </el-input>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="是否启用" :label-width="labelWidth">
        <el-switch
          v-model="baseInfo.state"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <h5 :style="{ marginLeft: labelWidth, color: '#F56C6C' }">
        海报禁用后对应的关键字也将禁用
      </h5>
      <el-form-item
        label="生成等待文字"
        :label-width="labelWidth"
        prop="wait_text"
      >
        <el-input v-model="baseInfo.wait_text" placeholder="请输入生成等待文字">
        </el-input>
      </el-form-item>
      <el-form-item
        label="生成成功文字"
        :label-width="labelWidth"
        prop="success_text"
      >
        <el-input
          v-model="baseInfo.success_text"
          placeholder="请输入生成成文字"
        >
        </el-input>
        <span class="tip">
          例如：您的专属海报已大功告成_! 您的专属推广链接：[link]<br />
          [link] 代表用户的专属推广链接，即通过这个链接就可以绑定他的客户
        </span>
      </el-form-item>
      <el-form-item
        label="公众号提示文字"
        :label-width="labelWidth"
        prop="mp_text"
      >
        <el-input v-model="baseInfo.mp_text" placeholder="公众号提示文字">
        </el-input>
      </el-form-item>
      <el-form-item>
        <!-- {{ baseInfo }} -->
        <div style="display: flex; justify-content: center">
          <el-button :loading="isSubmitLoading" type="primary" @click="submit"
            >提交</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Drag from "@/components/Drag";
import BtnImgUpload from "@/components/BtnImgUpload";
import { uploadUrl, baseUrl } from "@/api/common";
import { detail, add, edit } from "@/api/mpManage/mpPoster";
import _ from "lodash";
export default {
  name: "addPost",
  components: { Drag, BtnImgUpload },
  data() {
    return {
      id: "",
      uploadUrl: uploadUrl,
      baseInfoRules: {
        name: [{ required: true, message: "请输入海报名称", trigger: "blur" }],
        bg_img: [{ required: true, message: "请上传海报", trigger: "blur" }],
        keywords: [
          { required: true, message: "请输入生成海报关键字", trigger: "blur" },
        ],
      },
      curSelectMapBaseInfo: {
        nickname: "nickname_info",
        date: "date_info",
        time: "time_info",
        expire_time: "expire_time_info",
      },
      baseInfo: {
        avatar_info: {},
        qrcode_info: {},
        date_info: {
          font_size: 14,
          font_color: "#333",
        },
        time_info: {
          font_size: 14,
          font_color: "#333",
        },
        nickname_info: {
          font_size: 14,
          font_color: "#333",
        },
        expire_time_info: {
          font_size: 14,
          font_color: "#333",
        },
        wait_text: "您的专属海报正在拼命生成中，请等待片刻...",
        success_text: "您的专属海报已大功告成_!您的专属推广链接：[link] ",
        mp_text: "",
        bg_img: "",
        bg_img_show: "",
        state: 1,
      },
      info: {},
      labelWidth: "150px",
      isShowAvatar: false,
      isShowNickname: false,
      isShowQrcode: false,
      isShowDate: false,
      isShowTime: false,
      isShowExpireTime: false,
      isShowDelBtn: false,
      curSelect: "", //当前选中哪个海报元素
      isSubmitLoading: false,
      transStringFromJson: [
        "avatar_info",
        "nickname_info",
        "qrcode_info",
        "date_info",
        "time_info",
        "expire_time_info",
      ],
    };
  },
  computed: {
    getIsShowFontSet() {
      return (
        this.curSelect == "nickname" ||
        this.curSelect == "date" ||
        this.curSelect == "time" ||
        this.curSelect == "expire_time"
      );
      // return this.isShowNickname || this.isShowDate || this.isShowTime;
    },
    getMaxX() {
      return this.$refs.poster.getBoundingClientRect().width;
    },
    getMaxY() {
      return this.$refs.poster.getBoundingClientRect().height;
    },
    getCurDate() {
      const date = new Date();
      const year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      day = day.toString().padStart(2, 0);
      month = month.toString().padStart(2, 0);
      return `${year}-${month}-${day}`;
    },
    getCurTime() {
      const date = new Date();
      let h = date.getHours();
      let m = date.getMinutes();
      let s = date.getSeconds();
      h = h.toString().padStart(2, 0);
      m = m.toString().padStart(2, 0);
      s = s.toString().padStart(2, 0);
      return `${h}:${m}:${s}`;
    },
    getExpireTime() {
      return `过期时间：${this.getCurDate} ${this.getCurTime}`;
    },
  },
  created() {
    this.id = this.$route.query.id;
    console.log(this.id);
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      if (this.id) {
        this.getDetail();
      }
    },
    async getDetail() {
      const { data } = await detail(this.id);
      // console.log(data);
      this.transStringFromJson.forEach((item) => {
        if (data[item]) {
          data[item] = JSON.parse(data[item]);
        } else {
          data[item] = {};
        }
      });
      data.bg_img_show = baseUrl + "/" + data.bg_img;
      // this.baseInfo = _.assign(this.baseInfo, data);
      console.log(data);
      this.baseInfo = data;
      console.log(this.baseInfo.avatar_info);
      if (Object.keys(this.baseInfo.avatar_info).length) {
        this.isShowAvatar = true;
      }
      if (Object.keys(this.baseInfo.nickname_info).length) {
        this.isShowNickname = true;
      }
      if (Object.keys(this.baseInfo.qrcode_info).length) {
        this.isShowQrcode = true;
      }
      if (Object.keys(this.baseInfo.date_info).length) {
        this.isShowDate = true;
      }
      if (Object.keys(this.baseInfo.time_info).length) {
        this.isShowTime = true;
      }
      if (Object.keys(this.baseInfo.expire_time_info).length) {
        this.isShowExpireTime = true;
      }
    },
    eleClick(type) {
      this.curSelect = type;
      this.isShowDelBtn = true;
      console.log(this.curSelect, this.isShowDelBtn);
    },
    imgUploadSuccess(res) {
      console.log(res);
      if (res.code == 200) {
        this.baseInfo.bg_img_show = baseUrl + "/" + res.data.url;
        this.baseInfo.bg_img = res.data.url;
      } else {
        this.$message.error(res.msg || "上传失败");
      }
    },
    addEle(type, curSelect) {
      if (!this.baseInfo.bg_img) {
        this.$message.error("请上传海报底图");
        return false;
      }
      this[type] = true;
      this.curSelect = curSelect;
      this.baseInfo[this.curSelectMapBaseInfo[this.curSelect]].font_size = "14";
      this.baseInfo[this.curSelectMapBaseInfo[this.curSelect]].font_color =
        "#000000";
    },
    async del() {
      const map = {
        avatar: {
          flag: "isShowAvatar",
          text: "头像",
        },
        nickname: {
          flag: "isShowNickname",
          text: "昵称",
        },
        qrcode: {
          flag: "isShowQrcode",
          text: "二维码",
        },
        date: {
          flag: "isShowDate",
          text: "日期",
        },
        time: {
          flag: "isShowTime",
          text: "时分",
        },
        expire_time: {
          flag: "isShowExpireTime",
          text: "过期时间",
        },
        // expire_time: {
        //   flag: "isShowExpireTime",
        //   text: "过期时间",
        // },
      };
      const active = map[this.curSelect];
      console.log(active, this.curSelect);
      const alertRes = await this.$confirm(
        `确定要删除${active.text}吗?`,
        "提示"
      );
      console.log("alertRes", alertRes);
      if (alertRes == "confirm") {
        // 确定删除
        this[active.flag] = false;
        this.isShowDelBtn = false;
      }
    },
    getRectInfo() {
      const arr = [
        "avatar",
        "nickname",
        "qrcode",
        "date",
        "time",
        "expire_time",
      ];
      arr.forEach((item) => {
        const type = item + "_info";
        if (this.$refs[item]) {
          const el = this.$refs[item];
          this.baseInfo[type].left = el.dr.rect.offsetLeft;
          this.baseInfo[type].top = el.dr.rect.offsetTop;
          this.baseInfo[type].width = el.dr.rectWidth;
          this.baseInfo[type].height = el.dr.rectHeight;
        } else {
          this.baseInfo[type] = null;
        }
      });

      // console.log(this.baseInfo[type]);
    },
    goBack() {
      this.$router.back();
    },
    submit() {
      // 获取各个材料的数据传入后端
      this.$refs.baseInfo.validate(async (valid) => {
        if (valid) {
          // 验证是否存在二维码位置信息
          console.log(this.$refs.qrcode);
          if (!this.$refs.qrcode) {
            this.$message.error("请设置二维码位置");
            return false;
          }
          // 获取背景底图的宽高
          this.getRectInfo();
          const bgImgInfo = this.$refs.bgImg.getBoundingClientRect();
          console.log(
            this.$refs.bgImg.clientWidth,
            this.$refs.bgImg.clientHeight
          );
          console.log(bgImgInfo.clientWidth);
          // return false;
          const params = { ...this.baseInfo };

          params.bg_img_width = bgImgInfo.width;
          params.bg_img_height = bgImgInfo.height;

          // params.appid = this.$store.getters.curMpInfo.appid;
          this.transStringFromJson.forEach((item) => {
            if (params[item]) {
              params[item] = JSON.stringify(params[item]);
            }
          });

          console.log(params);
          this.isSubmitLoading = true;
          try {
            if (params.id) {
              await edit(params);
            } else {
              await add(params);
            }
            this.$message.success("操作成功!");
            this.goBack();
          } finally {
            this.isSubmitLoading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.poster {
  width: 375px;
  height: 600px;
  background-color: #faebd7;
  // overflow: hidden;
}
.right {
  margin-left: 60px;
  .tip {
    color: #f00;
  }
}
.mr_30 {
  margin-right: 30px;
}
@media screen and (max-width: 500px) {
  .poster_wrap {
    display: block !important;
  }
  .poster {
    width: 90% !important;
  }
  :deep(.el-form-item .el-form-item__label) {
    width: 80px !important;
  }
}
</style>
